import sys
import time
from PyQt5.QtWidgets import *
from study.HexDateTools.hex_date_tran import Ui_HexDateDialog
import re

class ImageDialog(Ui_HexDateDialog):
    def __init__(self):
        super(ImageDialog, self).__init__()

    def run_hex2date(self):  # 定义槽
        self.lineIn = self.lineEdit.text()
        self.textin_hex2date = self.lineIn.replace(' ', '') # replace只能作用于str
        for a_input in self.textin_hex2date:
            if re.match('[a-zA-Z0-9]', a_input, 0) is None:
                return self.textBrowser.append('输入hex含有非法字符！')
            #也可以是elif a_input in 'ghijklmnopqrstuvwxyzGHIJKLMNOPQRSTUVWXYZ':
            elif re.match('[ghijklmnopqrstuvwxyzGHIJKLMNOPQRSTUVWXYZ]',a_input,0) is not None:
                return self.textBrowser.append('输入hex不得含有a-fA-F以外的字母。')
        try:
            self.c_time = int(self.textin_hex2date, 16)
            print(self.c_time)
            if self.c_time >= 32472115200:
                return self.textBrowser.append('日期大于2999-01-01 00:00:00！')
            self.b_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.c_time))  # %Y表示1999,y为00
            self.textBrowser.append('%s' % self.b_time)
        except ValueError:
            self.textBrowser.append('无法计算！')

    def run_now2hex(self):  # 定义槽
        self.local_struct_time = time.localtime()  # strptime localtime gmtime都生成struct_time类型
        self.local_hex = hex(int(time.mktime(self.local_struct_time)))
        self.local_date = time.strftime('%Y-%m-%d %H:%M:%S', self.local_struct_time) #%Y表示1999,y为00
        self.textBrowser.append('当前日期：%s' % self.local_date)
        self.textBrowser.append('%s' % self.local_hex)

    def run_date2hex(self):  # 定义槽
        self.date_enter = self.dateTimeEdit.text()
        if self.date_enter >= '2999-01-01 00:00:00':
            return self.textBrowser.append('日期不得大于2999-01-01 00:00:00！')
        try:
            self.enter_struct_date = time.strptime(self.date_enter, "%Y-%m-%d %H:%M:%S" ) #strptime localtime gmtime都生成struct_time类型
            self.enter_date_hex = hex(int(time.mktime(self.enter_struct_date)))  # 转换为时间戳
            self.textBrowser.append(self.enter_date_hex)
        except ValueError:
            self.textBrowser.append('不得早于1970-01-01 00:00:00！')

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = QWidget()
    ui = ImageDialog()
    ui.setupUi(widget)
    widget.show()
    sys.exit(app.exec_())